"use strict";
/**
 * @name friend
 * 好友系统
 */


/**
 * @name search
 * @param string name 玩家昵称
 * @param string uid 玩家唯一标识,有uid优先以uid为准
 * @param string key 额外字段,多个以","分割
 * 好友搜索
 */
exports.search = async function () {
    let uid = this.get('uid');
    let name = this.get('name');
    let key = this.get('key', 'string') || '';
    if (!uid && !name) {
        return this.error('error', 'args empty');
    }
    // let arr_uid = uid.split(',').filter(u => u.length > 0);
    // if (arr_uid.length < 1) {
    //     return this.error("uid empty")
    // }
    let fk = ['_id'];
    let arr_key = key.split(",");
    for (let k of arr_key) {
        if (k) fk.push(k);
    }

    let role = this.model.mongo('role', this.sid);
    if (uid) {
        let data = await role.get(uid, fk).then();
        if (data == null) {
            return [];
        } else {
            return [data];
        }
    } else if (name) {
        return role.findFromName(name, fk);
    } else {
        return this.error("args error");
    }
}



/**
 * @name recommendFriend
 * @param int num 拉取的玩家ID数量，1<=num<=100
 * @param string key 额外字段
 * 好友推荐列表
 */
exports.recommendFriend = function () {
    let num = this.get('num', 'int') || 1;
    if (num > 100) {
        num = 100;
    }
    return Promise.resolve().then(() => {
        let query = { "uid": this.uid, "val": 1 }
        let option = { "multi": true, "dataType": "array", "fields": { "_id": -1, "fid": 1 } };
        let friend = this.model.mongo("friend", this.sid);
        return friend.find(query, option);
    }).then(ret => {
        let arr = [];
        if (ret.length != 0) {
            for (let d of ret) {
                arr.push(d.fid);
            }
        }
        let key = this.get('key', 'string')
        let role = this.model.mongo("role", this.sid);
        let fields = { "_id": 1 };
        let time = new Date().getTime() - 7 * 24 * 60 * 60 * 1000;
        //筛选已经是好友的uid
        arr.push(this.updater.uid);
        let query = { "login": { "$gt": time }, "_id": { "$ne": arr } };
        if (key) {
            let arrKey = key.split(",");
            for (let k of arrKey) {
                fields[k] = 1;
            }
        }
        return role.aggregate([
            { $sample: { size: num } },
            { $match: query },
            { $project: fields }
        ], {})
    })
}



/**
 * @name getter
 * @param int val 类型：-1：我发出的申请，0：等待我确认的申请,1:正式好友
 * @param string key 额外字段
 * 好友列表
 */

exports.getter = function () {
    let val = this.get('val', 'number') || 0;
    let key = this.get('key', 'string')
    return Promise.resolve().then(() => {
        let query = { "uid": this.uid, "val": val }
        let option = { "multi": true, "dataType": "array", "fields": { "_id": -1, "fid": 1, "bak": 1 } };
        let friend = this.model.mongo("friend", this.sid);
        return friend.find(query, option);
    }).then(async ret => {
        if (ret.length === 0) {
            return ret;
        }
        if (val == 1) {
            this.updater.record.max(52, ret.length);
            await this.updater.save();
        }
        let arr = [];
        for (let d of ret) {
            arr.push(d.fid);
        }
        let role = this.model.mongo("role", this.sid);
        let fields = { "name": 1 };
        let query = { "_id": { "$in": arr } };
        let option = { "multi": true, "dataType": "array", "fields": fields };
        if (key) {
            let arrKey = key.split(",");
            for (let k of arrKey) {
                fields[k] = 1;
            }
        }
        return role.find(query, option).then((friendList) => {
            for (let k in ret) {
                if (ret[k].bak != "") {
                    for (let j in friendList) {
                        if (friendList[j]._id == ret[k].fid) {
                            friendList[j].bak = ret[k].bak;
                        }
                    }
                }
            }
            return friendList;
        });
    })
}

/**
 * @name add
 * @param string fid 好友ID
 * 添加好友
 */

exports.add = function () {
    let fid = this.get('fid');
    if (!fid) {
        return this.error('fid not exist');
    }
    if (this.uid === fid) {
        return this.error('is self');
    }
    // let config = this.config("friend");
    // if( !config ){
    //     return this.error("friend disabled");
    // }

    this.friend = this.model.mongo("friend", this.sid);
    return this.friend.uget(this.uid, fid).then(r => {
        if (r) {
            return this.error("friend_record_exist", fid, r['val'])
        }
        else {
            return verify_friend_number.call(this, fid);
        }
    }).then(r => {
        return this.friend.apply(this.uid, fid).then(() => 1);
    })
}



/**
 * @name refuse
 * @param string fid 申请人UID，空：一键拒绝
 * 拒绝申请
 * 拒绝申请时调用此接口直接删除
 * 好友系统不需要验证时，不要调用此接口
 */
exports.refuse = function () {
    let fid = this.get('fid');
    let friend = this.model.mongo("friend", this.sid);
    return friend.refuse(this.uid, fid);
}


/**
 * @name accept
 * @param string fid 申请人UID
 * 通过申请
 */
exports.accept = function () {
    let fid = this.get('fid', 'string');
    if (!fid) {
        return this.error('fid empty');
    }
    // let config = this.config("friend");
    // if(!config || config["apply"].val == 1){
    //     return this.error("friend_submit_disable")
    // }
    let locks = this.model.redis("locks", this.sid, "friend");

    this.friend = this.model.mongo("friend", this.sid);
    return this.friend.uget(this.uid, fid).then(r => {
        if (!r || r["val"] > 0) {
            return this.error("friend_apply_empty", fid);
        }
        else {
            return locks.start([this.uid, fid]);
        }
    }).then(r => {
        if (r.length > 0) {
            return this.error("friend_submit_locked", r);
        }
        else {
            return verify_friend_number.call(this, fid);
        }
    }).then(r => {
        return this.friend.accept(this.uid, fid);
    }).then(r => {
        return locks.clear().then(() => r);
    })
}


/**
 * @name remove
 * @param string fid 好友UID
 * 删除好友
 */
exports.remove = function () {
    let fid = this.get('fid');
    if (!fid) {
        return this.error('fid empty');
    }
    let removeConfig = this.config.get("friend.remove");
    let friend = this.model.mongo("friend", this.sid)
    if (!removeConfig) {
        return friend.udel(this.uid, fid);
        // return friend.del(fid);
    }
    this.updater.daily.add("deleteFriend." + removeConfig['key'], 1);
    return this.updater.data().then(r => {
        let DRMVal = this.updater.daily.get("deleteFriend." + removeConfig['key']) || 0;
        if (DRMVal >= removeConfig['val']) {
            return this.error("friend_remove_limit", DRMVal, removeConfig['val'])
        }
    }).then(r => {
        return friend.del(this.uid, fid);
    }).then(r => {
        return this.updater.save()
    })
}

function verify_friend_number(fid, callback) {
    // let config = this.config("friend");
    // if(!config){
    //     return callback("config_not_exist","friend");
    // }

    let arr = [this.uid, fid];

    let keys = ["_id"];
    // let limit = this.config("base","friendNumMax").val;
    // if(Array.isArray(limit) && limit[0]){
    //     keys.push(limit[0]);
    // }
    let role = this.model.mongo("role", this.sid);
    let roles;
    return role.get(arr, keys)
        .then(r => {
            roles = r;
            if (!roles || !roles[fid]) {
                return this.error("user_not_exist", fid)
            }
            else {
                return this.friend.sum(arr, 1);
            }
        })
        .then(count => {
            //检查自己
            let selfMaxNum = sum_friend_number.call(this, roles[this.uid]);
            if (count[this.uid] && count[this.uid]["num"] >= selfMaxNum) {
                return this.error('friend_max_self', [count[this.uid]["num"], selfMaxNum]);
            }
            //检查对方,非关注模式
            // if (config['apply'] > 0) {
            let targetMaxNum = sum_friend_number.call(this, roles[fid])
            if (count[fid] && count[fid]["num"] >= targetMaxNum) {
                return this.error('friend_max_target', [count[fid]["num"], targetMaxNum]);
            }
            // }
            return this.friend.sum(count[fid], 0);
        }).then(count => {
            //检查自己
            // let selfMaxNum = sum_friend_number.call(this,config,roles[this.uid]);
            // if( count[this.uid] && count[this.uid]["num"] >= selfMaxNum ){
            //     return this.error('friend_max_self', [count[this.uid]["num"] , selfMaxNum]);
            // }
            //检查对方的好友申请数量上限
            // let selfMaxNum = sum_friend_number.call(this,config,roles[this.uid]);

            let config = this.config("friend");
            if (count && count["num"] >= config.receivedFriendRequestNumMax) {
                return this.error('friend_max_self', [count[this.uid]["num"], selfMaxNum]);
            }
            return count;
        })
}


//计算好友最大数量
function sum_friend_number(role) {
    let config = this.config("friend");

    return config.friendNumMax;
    // let limit = config['limit'];
    // if( !role || !Array.isArray(limit)){
    //     return 0;
    // }
    // if(!limit[0]){
    //     return parseInt(limit[1]);
    // }
    // let key = limit[0];
    // let val = role[key]||0;
    // let UConfig = this.config('level', val);
    // if (!UConfig){
    //     return 0;
    // }
    // return UConfig[limit[1]]||0;
}




/**
 * @name like
 * @param array fidList 好友列表
 * 点赞好友
 */
exports.like = async function () {
    // let fid = this.get('fid', 'string');    
    // if (!fid) {
    //     return this.error('fid empty');
    // }
    // //加友情点数
    // this.updater.daily.key("like");
    // await this.updater.data();
    // let likeList=this.updater.daily.get("like")||{};
    // let num = 0;
    // for(let key in likeList){
    //     num++;
    // }
    // if(num>this.config("base","likesMaxNum").val){
    //     return this.error("今日点赞次数已满",likeList.length);
    // }
    // this.friend = this.model.mongo("friend",this.sid);
    // let fData = await this.friend.uget(this.uid,fid);
    // if(!fData || fData["val"]<=0){
    //     return this.error("无法给此人点赞",fid);
    // }
    // let role = this.model.mongo("role",this.sid);
    // let like = await role.get(fid,["like"]).then();
    // like["like"] += 1;
    // await role.set(fid,"like",like["like"]);
    // this.updater.daily.add("like."+fid,1);
    // this.updater.record.add(36,1);
    // return this.updater.save();


    // let fid = this.get('fid', 'string');
    // if (!fid) {
    //     return this.error('fid empty');
    // }
    const fidList = this.get('fidList', 'array');
    if (!fidList) {
        return this.quick_error('M2saghge140', ' 参数错误');
    }

    //check-今日给别人点赞的总次数
    let totalLike = this.updater.daily.get('totalLike');
    if (totalLike > 200) {
        return this.error('今日给他人点赞已达上限，请明日再来～');
    }
    //check-今日是否已经给此人点过赞
    this.updater.daily.key("like");
    this.updater.daily.key("sendGift");
    await this.updater.data();
    let like = this.updater.daily.get('like') || {};//{"uid":1,"uid2":1}
    let likedRole = this.model.mongo('role', this.sid);
    let sendGiftList = this.updater.daily.get("sendGift") || {};
    let config = this.config("friend");
    for (let k in fidList) {
        let fid = fidList[k];
        if (like[fid]) {
            return this.error("无法给此人点赞", fid);
        }
        this.updater.daily.set('totalLike', totalLike++);
        this.updater.daily.set('like.' + fid, 1);
        //给被点赞玩家的点赞数like +1
        let likeCount = await likedRole.get(fid, ['like']).then();
        likeCount['like'] += 1;
        await likedRole.set(fid, "like", likeCount['like']);
        if (sendGiftList[fid]) {
            return this.error("已经给此人送过礼物了", fid);
        }
        let num = 0;
        for (let key in sendGiftList) {
            num++;
        }
        if (num > config.giftMaxNum) {
            return this.error("今日送礼次数已满", sendGiftList.length);
        }
        this.friend = this.model.mongo("friend", this.sid);
        let fData = await this.friend.uget(this.uid, fid);
        // if (!fData || fData["val"] <= 0) {
        //     continue;
        // }
        sendGiftList[fid] = 1;
        this.updater.daily.set("sendGift", sendGiftList);
        //给奖励给自己
        this.updater.item.add(60100003, config.fpSendNum.val);
        let friendGiftCache = this.model.redis("friendGift", this.sid);
        // 待优化哦
        let ttl = 1 * 24 * 3600; //有效期1天
        let friendKey = fid + "|" + this.library("time/sign");
        await friendGiftCache.set(friendKey, this.uid, 1, ttl);
        //待优化哦
        await friendGiftCache.expire(friendKey, ttl);
    }
    return this.updater.save();
}




// /**
//  * @name cardLike
//  * @param string fid 对方的UID
//  * 名片点赞
//  */
// exports.cardLike = async function () {
//     let fid = this.get('fid', 'string');
//     if (!fid) {
//         return this.error('fid empty');
//     }
//     //check-今日给别人点赞的总次数
//     let totalLike = this.updater.daily.get('totalLike');
//     if (totalLike > 200) {
//         return this.error('今日给他人点赞已达上限，请明日再来～');
//     }
//     //check-今日是否已经给此人点过赞
//     this.updater.daily.key("like." + fid);
//     await this.updater.data();
//     let like = this.updater.daily.get('like.' + fid);//{"uid":1,"uid2":1}
//     if (like) {
//         return this.error('今日已经给该玩家点赞，请明日再来～', fid);
//     }

//     this.updater.daily.set('totalLike', totalLike++);
//     this.updater.daily.set('like.' + fid, 1);
//     //给被点赞玩家的点赞数like +1
//     let likedRole = this.model.mongo('role', this.sid);
//     let likeCount = await likedRole.get(fid, ['like']).then();
//     likeCount['like'] += 1;
//     await likedRole.set(fid, "like", likeCount['like']);

//     return this.updater.save();
// }


// /**
//  * @name sendGift
//  * @param array fidList 好友列表
//  * 好友送礼
//  */
// exports.sendGift = async function () {
//     const fidList = this.get('fidList', 'array');
//     if (!fidList) {
//         return this.quick_error('M2saghge140', ' 参数错误');
//     }
//     //加友情点数
//     this.updater.daily.key("sendGift");
//     await this.updater.data();
//     let sendGiftList = this.updater.daily.get("sendGift") || {};
//     let config = this.config("friend");
//     for (let k in fidList) {
//         let fid = fidList[k];
//         if (sendGiftList[fid]) {
//             return this.error("已经给此人送过礼物了", fid);
//         }
//         let num = 0;
//         for (let key in sendGiftList) {
//             num++;
//         }
//         if (num > config.giftMaxNum) {
//             return this.error("今日送礼次数已满", sendGiftList.length);
//         }
//         this.friend = this.model.mongo("friend", this.sid);
//         let fData = await this.friend.uget(this.uid, fid);
//         if (!fData || fData["val"] <= 0) {
//             continue;
//         }
//         sendGiftList[fid] = 1;
//         this.updater.daily.set("sendGift", sendGiftList);
//         //给奖励给自己
//         this.updater.item.add(60100003, config.fpSendNum.val);
//         let friendGiftCache = this.model.redis("friendGift", this.sid);
//         // 待优化哦
//         let ttl = 1 * 24 * 3600; //有效期1天
//         let friendKey = fid + "|" + this.library("time/sign");
//         await friendGiftCache.set(friendKey, this.uid, 1, ttl);
//         //待优化哦
//         await friendGiftCache.expire(friendKey, ttl);
//     }
//     return this.updater.save();
// }



/**
 * @name getGift
 * @param string fid 好友ID
 * 好友收礼
 */
exports.getGift = async function () {
    let fid = this.get('fid', 'string');
    let config = this.config('friend');
    if (!config) {
        return this.quick_error('好友配置不存在');
    }
    if (!fid) {
        //全收
        let friendGiftCache = this.model.redis("friendGift", this.sid);
        let friendKey = this.uid + "|" + this.library("time/sign");
        let friendCacheData = await friendGiftCache.get(friendKey) || {};
        let num = 0;
        for (let fid in friendCacheData) {
            this.updater.daily.key("getfriendGift");
            await this.updater.data();
            let getfriendGiftList = this.updater.daily.get("getfriendGift") || {};
            if (getfriendGiftList[fid]) {
                continue;
            }
            if (!friendCacheData[fid]) {
                continue;
            }
            // for (let key in getfriendGiftList) {
            num++;
            // }
            //今日最大收礼物次数的字段 等waca新字段
            if (num > config.beGiftMaxNum.val) {
                continue;
            }
            getfriendGiftList[fid] = 1;
            this.updater.item.add(60100003, config.fpGetNum.val);
            this.updater.daily.set('getfriendGift', getfriendGiftList);
        }
        // return this.updater.save();
    } else {
        //加友情点数
        this.updater.daily.key("getfriendGift");
        await this.updater.data();
        let getfriendGiftList = this.updater.daily.get("getfriendGift") || {};
        if (getfriendGiftList[fid]) {
            return this.error("已经收过礼物了哦", fid);
        }
        let friendGiftCache = this.model.redis("friendGift", this.sid);
        let friendKey = this.uid + "|" + this.library("time/sign");
        let friendCacheData = await friendGiftCache.get(friendKey) || {};
        if (!friendCacheData[fid]) {
            return this.error("这个人没送礼物给你哦", fid);
        }

        let num = 0;
        for (let key in getfriendGiftList) {
            num++;
        }
        //今日最大收礼物次数的字段
        if (num > config.beGiftMaxNum.val) {
            return this.error("今日送礼次数已满", getfriendGiftList.length);
        }
        //给奖励给自己
        getfriendGiftList[fid] = 1;
        this.updater.item.add(60100003, config.fpGetNum.val);
        this.updater.daily.set('getfriendGift', getfriendGiftList);
    }
    return this.updater.save();
}


/**
 * @name getGiftList
 * 收到礼物列表
 */
exports.getGiftList = async function () {
    let friendGiftCache = this.model.redis("friendGift", this.sid);
    let friendKey = this.uid + "|" + this.library("time/sign");
    let friendCacheData = await friendGiftCache.get(friendKey) || {};
    return friendCacheData;
}



/**
 * @name setBakName
 * @param string fid 好友ID
 * @param string bak 备注
 * 好友备注
 */
exports.setBakName = async function () {
    let fid = this.get('fid', 'string');
    let bak = this.get('bak', 'string');
    if (!fid || !bak) {
        return this.error('fid empty');
    }
    this.friend = this.model.mongo("friend", this.sid);
    return this.friend.uget(this.uid, fid).then(r => {
        if (!r || r["val"] > 0) {
            return this.friend.uset(this.uid, fid, "bak", bak);
        }
        else {
            return this.error("friend_apply_empty", fid);
        }
    }
    )
}
